class ListNode {
    int val;
    //套定义ListNode类型
    ListNode next;
    ListNode(int x) { val = x; }
}

public class RemoveLinkedListElements {
    public static void main(String[] args) {
        // 创建一个测试链表 1 -> 2 -> 6 -> 3 -> 4 -> 5 -> 6
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(6);
        head.next.next.next = new ListNode(3);
        head.next.next.next.next = new ListNode(4);
        head.next.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next.next = new ListNode(6);

        int val = 6;
        //调用内部类中的方法
        ListNode result = Solution.removeElements(head, val);

        // 打印结果链表
        while (result != null) {
            System.out.print(result.val + " ");
            result = result.next;
        }
    }

    static class Solution {
        public static ListNode removeElements(ListNode head, int val) {
            // 不断刷新头结点，使其不为 val
            while (head != null && head.val == val) {
                head = head.next;
            }

            if (head == null) {
                return null;
            }
            // 定义指针
            ListNode tool = head;

            while (tool.next != null) {
                if (tool.next.val == val) {
                    // 跳过值为 val 的下节点
                    tool.next = tool.next.next;
                } else {
                    // 直接用 head 会改变头节点
                    tool = tool.next;
                }
            }

            return head;
        }
    }
}
